<?php
class UserController extends AppController {

	public $name = 'user';
	public $kcaptcha_components = array('captcha');	
	public $micool_components = array('micool');	
	//public $index_behaviors = array('post');
		
	function beforeFilter() {
	    parent::beforeFilter(); 
		$this->C_auth->autoRedirect = false; //For override login
	    $this->C_auth->allowedActions = array('index','login','agreement','reg','forgot','kcaptcha','micool'/*,'logout,' ,'getareas','passwd','profile','shoprequest','getshopcategories','shopinfo','shopnotice','buyorderadress','userorder','userdoorder','userordersuccess','usermyorder','paymentmsg','userorderdel','askbackmoney','complaint','userorderview','getbackmoney','surebackmoney','userordercheckget','userprotectrights','usercancelprotect','favorite','favoritedel','address','deladdress' */);

	}

	public function micool()
    {
        $this->C_micool->render(); 
    }	
	
	public function login() {

		if ($this->C_auth->user()) {
			$userID = $this->C_auth->user('id');			
			$this->redirect($this->C_auth->redirect());
		} else if (!empty($this->data)) {
 		    //Loader::import('pspframework.utils.Sanitize');
		   // $safeData = Sanitize::clean($this->data); 
			//print_r($this->data);
		    if ( md5(strtolower($this->data['user']['captcha'])) == $this->C_session->read('captcha') ) {
				$this->set('invalidCaptcha', 0);
			    $safeData = $this->data;
			    $this->C_auth->login($safeData); // autologin
			    $userID = $this->C_auth->user('id');				
			    if ($userID) {				
				    $this->redirect($this->C_auth->redirect());
			    } else {
				    $this->set('msg', '用户名不存在或是密码错误!');
			    }
		    } else {
				$this->set('invalidCaptcha', 1);
            }			

		}	
	}	

	function logout() {
		$userID = $this->C_auth->user('id');
		$this->redirect($this->C_auth->logout());	
	}		
	
	public function agreement() {

	}
	
	public function index() {
       //$t = POP::exe('[M@:word alluser]',array('1'=>'44'));
        //print_r($t);
	}
	
	public function forgot() {
	    $do = Request::get_args('do');
		$msg = '';
		if($do =='forgot3') {
		    $user_email = Request::get_args('user_email');
            if(!$user_email){
	            $msg = '邮箱为空!';
            }
            if(!$this->check_email_address($user_email)){
                $msg = "您填写的邮箱格式不正确";
            }
			if ( md5(strtolower(Request::get_args('veriCode'))) != $this->C_session->read('captcha') ) {
			    $msg = "验证码错误!";
			}
			if(empty($msg)) {
				$query = array(
					'conditions' => array('user.email' => $user_email), 
					'fields' => array('user.*'), 
				);
				$oneuserinfo = POP::exe('[@@:UM user][@@:QU find:first]',$query);				
                if(!empty($oneuserinfo)) {
                    $pwd = substr(md5(rand(0, 8).$oneuserinfo['user']['username']),0,8);
					$safeData['user']['password'] = $this->C_auth->password($pwd); 
					$query  = array();		
					$query['keyid'] = $oneuserinfo['user']['id'];				
					$query['set'] = $safeData;		
					if(POP::exe('[@@:UM user][@@:QU save]',$query)) {									
					    $this->_sendGetPasswdConfirmEmail($user_email, $oneuserinfo['user']['username'] ,$pwd);
                        $msg = "提交成功,请进入你的邮箱查看密码,请及时修改密码!";						
					}
					
                }else {
				    $msg = "邮箱不存在!";
                }				
			}			
		}
		$this->set('msg',$msg);

	}	

	function check_email_address($email) {
		// First, we check that there's one @ symbol, and that the lengths are right
		if (!ereg("[^@]{1,64}@[^@]{1,255}", $email)) {
			// Email invalid because wrong number of characters in one section, or wrong number of @ symbols.
			return false;
		}
		// Split it into sections to make life easier     
		$email_array = explode("@", $email);
		$local_array = explode(".", $email_array[0]);
		for ($i = 0; $i < sizeof($local_array); $i++) {
			if (!ereg("^(([A-Za-z0-9!#$%&'*+/=?^_`{|}~-][A-Za-z0-9!#$%&'*+/=?^_`{|}~\.-]{0,63})|(\"[^(\\|\")]{0,62}\"))$", $local_array[$i])) {     
			return false;
			}
		}
		if (!ereg("^\[?[0-9\.]+\]?$", $email_array[1])) { // Check if domain is IP. If not, it should be valid domain name     
		$domain_array = explode(".", $email_array[1]);
			if (sizeof($domain_array) < 2) {
			return false; // Not enough parts to domain
			}
			for ($i = 0; $i < sizeof($domain_array); $i++) {
				if (!ereg("^(([A-Za-z0-9][A-Za-z0-9-]{0,61}[A-Za-z0-9])|([A-Za-z0-9]+))$", $domain_array[$i])) {
				return false;
				}
			}
		}
		return true;
	} 	
	
	public function passwd() {
	    $this->set('msg', '');
		if (!empty($this->data)) {		
			$query = array(
				'conditions' => array('user.id' => $this->my->id), 
				'fields' => array('user.password'), 
			);
			$curPassWD = POP::exe('[@@:UM user][@@:QU find:first]',$query);			
			if ($this->C_auth->password($this->data['user']['oldpassword']) != $curPassWD['user']['password']) {
				$this->set('msg', '原始密码错误！');
			} else {			
				$query  = array();		
				$query['keyid'] = $this->my->id;				
				$query['set']['user'] = array('password' => $this->C_auth->password($this->data['user']['password1']));		
				if(POP::exe('[@@:UM user][@@:QU save]',$query)) {			
					$this->set('msg', '密码修改成功！');
				} else {
					$errors = $this->user->invalidFields();
					$msg = '';
					foreach ($errors as $errmsg) {
						$msg .= $errmsg.'<br />';
					}
					$this->set('msg', $msg);
				}
			}
		}	
	}
	
	public function profile() {	
		if (!empty($this->data)) {
			$query = array(
				'conditions' => array('userinfo.user_id' => $this->my->id), 
				'fields' => array('userinfo.*'), 
			);
			$oneuserinfo = POP::exe('[@@:UM userinfo][@@:QU find:first]',$query);
			$this->data['userinfo']['user_id'] = $this->my->id;	
			
			$query  = array();				
			if(!empty($oneuserinfo)) {	
				$query['keyid'] = $oneuserinfo['userinfo']['id'];				
				$query['set'] = $this->data;					
			}else {			
				$query = $this->data;		
			}
			if(POP::exe('[@@:UM userinfo][@@:QU save]',$query)) {
                $this->flash('修改成功！', Router::url('user/profile')); 
			} else {
                $this->flash('修改失败！', Router::url('user/profile')); 			
			} 
		}	

		$query = array(
			'conditions' => array('userinfo.user_id' => $this->my->id), 
			'fields' => array('userinfo.*'), 
		);
		$oneuserinfo = POP::exe('[@@:UM userinfo][@@:QU find:first]',$query);	
		$query = array(
			'fields' => array('area.*'), 
		);
		$return_array = POP::exe('[@@:UM area][@@:QU find:all]',$query);			
	    $areas_info = array();		
	    foreach($return_array as $k=>$v) {
		    $areas_info[$v['area']['area_type']][$v['area']['id']]['id'] = $v['area']['id'];
		    $areas_info[$v['area']['area_type']][$v['area']['id']]['parent_id'] = $v['area']['parent_id'];
		    $areas_info[$v['area']['area_type']][$v['area']['id']]['area_name'] = $v['area']['area_name'];
		    $areas_info[$v['area']['area_type']][$v['area']['id']]['area_type'] = $v['area']['area_type'];
	    }
		$this->set('areas_info', $areas_info);
		$this->set('oneuserinfo', $oneuserinfo);		
	}

	public function reg($step=0) {
	    $step = intval($step);
        if($step==0) {
		    $step='';
		}
		if($step ==1 && empty($this->my)) {
		    if (!empty($this->data)) {		    
				if ( md5(strtolower($this->data['user']['captcha'])) == $this->C_session->read('captcha') ) {
					$query = array(
						'conditions' => array('user.email' => $this->data['user']['email']), 
						'fields' => array('user.*'), 
					);
					$isemaill = POP::exe('[@@:UM user][@@:QU find:first]',$query);
					$query = array(
						'conditions' => array('user.username' => $this->data['user']['username']), 
						'fields' => array('user.*'), 
					);
					$isuername = POP::exe('[@@:UM user][@@:QU find:first]',$query);				
					if(empty($isuername)) {
						if(empty($isemaill)) {						    
							$this->set('invalidCaptcha', 0);
							$this->data['user']['password'] = $this->C_auth->password($this->data['user']['password1']); 
							$this->data['user']['groupid'] = Param::read('GroupType.common.id');
							$this->data['user']['rank_id'] = 1;
							//Loader::import('pspframework.utils.Sanitize');
							//$safeData = Sanitize::clean($this->data);  						
							$safeData = $this->data;	
			                if(POP::exe('[@@:UM user][@@:QU save]',$safeData)) {							
								$this->C_auth->login($safeData); // autologin
								$userID = $this->C_auth->user('id'); 
								$step =1;							
							} else {
								$step ='';
							}
						} else {
							$this->set('isemaill','该邮箱地址已经存在了!');
							$step ='';
						}	
					} else {
						$this->set('isuername','该用户名已经存在了!');
						$step ='';
					}					
				} else {
					$this->set('invalidCaptcha', 1);
					$step ='';
                }			    				
		    } else {
                $step ='';
            }            
		}	
		if($step ==1 && !empty($this->my)) {
			$this->data['user']['email'] = $this->my->email; 
		    $this->data['user']['username'] = $this->my->username;
        }
	
		$this->render('reg'.$step);
	}

    function shopinfo()
    {
	    $this->_teamRights();
		$query = array(
			'conditions' => array('shopinfo.user_id' => $this->my->id), 
			'fields' => array('shopinfo.*'), 
		);
		$shop_info = POP::exe('[@@:UM shopinfo][@@:QU find:first]',$query);		
	    if (!empty($this->data)) {
			$query = array(
				'conditions' => array('AND' => array('shopinfo.user_id<>' => $this->my->id, 'shopinfo.shop_name' => $this->data['shopinfo']['shop_name'])), 
				'fields' => array('shopinfo.*'), 
			);
			$tempshopinfo = POP::exe('[@@:UM shopinfo][@@:QU find:first]',$query);					      
            if(isset($tempshopinfo['shopinfo']['id'])) {
                $errormsg = '店铺名有相同的'; 
            }else {				
		        if (!empty($_FILES)) {
                $post = array(); 					
			    foreach($_FILES as $key=> $value)
				{			
                    $upload_name = $key;
                    $uploadErrors = array(
                        0=>"文件上传成功",
                        1=>"上传的文件超过了 php.ini 文件中的 upload_max_filesize directive 里的设置",
                        2=>"上传的文件超过了 HTML form 文件中的 MAX_FILE_SIZE directive 里的设置",
                        3=>"上传的文件仅为部分文件",
                        4=>"没有文件上传",
                        6=>"缺少临时文件夹"
	                );				
	                if (!isset($_FILES[$upload_name])) {
/* 		                    echo ("没有发现文件 ");
		                    exit(0); */
							continue;
	                } else if (isset($_FILES[$upload_name]["error"][0]) && $_FILES[$upload_name]["error"][0] != 0) {
/* 		                    echo ($uploadErrors[$_FILES[$upload_name]["error"][0]]);
		                    exit(0); */
							continue;
	                } else if (!isset($_FILES[$upload_name]['name'][0])) {
/* 		                    echo ("文件无名称");
		                    exit(0); */
							continue;
	                }
                    Loader::import('lib.cupload');		
	                $up = new upload('jpg|gif|png|jpge',1024, $upload_name);
	                $up->set_dir(APP_ROOT . Param::read('upfiles.path') . '/license/','{y}/{m}/{d}');
	                $fs=$up->execute();	
	                $realtxt=$fs[0];
					$rootpath = trim(str_replace(Param::read('wwwrootPatch'),"",Param::read('htdocPatch')),'/') ;
					$rootpath = !empty($rootpath)?	('/'.$rootpath) : '';					
	                if($realtxt['flag']==1){
		                $fileSrcStr= $rootpath . str_replace(APP_ROOT,"",$realtxt['dir']).$realtxt['name'];
		                $post[$key]['img_url'] = $fileSrcStr;
	                }else if($realtxt[flag]==-1||$realtxt[flag]==-2){
		                    echo ('文件上传关闭');
	                }
			    }
				isset($post['doc']['img_url']) && !empty($post['doc']['img_url']) && $this->data['shopinfo']['shop_images'] = $post['doc']['img_url']; 				
				isset($post['doc1']['img_url']) && !empty($post['doc1']['img_url']) && $this->data['shopinfo']['shop_logo'] = $post['doc1']['img_url']; 
				isset($post['doc2']['img_url']) && !empty($post['doc2']['img_url']) && $this->data['shopinfo']['shop_template_img'] = $post['doc2']['img_url']; 			
			    }	
				$company_maps = Request::get_args('company_maps');
				list($position_x,$position_y)=explode(',',$company_maps);				
				if(!empty($position_x)|| !empty($position_y)) {
                    $this->data['shopinfo']['now_x'] = $position_x;
                    $this->data['shopinfo']['now_y'] = $position_y;		
				}
                $this->data['shopinfo']['map_x'] = $this->data['shopinfo']['now_x'];
                $this->data['shopinfo']['map_y'] = $this->data['shopinfo']['now_y'];				
                $this->data['shopinfo']['user_id'] = $this->my->id;
                $this->data['shopinfo']['id'] = $this->my->id;
                !isset($this->data['shopinfo']['categories']) && $this->data['shopinfo']['categories'] =0;
				$this->data['shopinfo']['shop_categories'] =$this->data['shopinfo']['categories'];
                if($this->data['shopinfo']['shop_categories']==0){
	                $this->data['shopinfo']['shop_categories'] =$this->data['shopinfo']['categories_parent'];
                }
                unset($this->data['shopinfo']['categories'],$this->data['shopinfo']['categories_parent'],$this->data['shopinfo']['now_x'],$this->data['shopinfo']['now_y']);	


				$query  = array();				
				if(isset($shop_info['shopinfo']['id'])) {	
					$query['keyid'] = $shop_info['shopinfo']['id'];				
					$query['set'] = $this->data;					
				}else {			
					$query = $this->data;		
				}
				if(POP::exe('[@@:UM shopinfo][@@:QU save]',$query)) {
					$this->flash('修改成功！', Router::url('user/shopinfo')); 
				} else {
					$this->flash('修改失败！', Router::url('user/shopinfo')); 			
				} 
				
            }			

        }
		$query = array(
			'conditions' => array('shopinfo.user_id' => $this->my->id), 
			'fields' => array('shopinfo.*'), 
		);
		$shop_info = POP::exe('[@@:UM shopinfo][@@:QU find:first]',$query);			

		$query = array(
			'conditions' => array('shopcategories.parent_id' => 0), 
			'fields' => array('shopcategories.*'), 
		);
		$shop_categories_parent = POP::exe('[@@:UM shopcategories][@@:QU find:all]',$query);	

        $categories_parent = 0;
        $categories_child = 0;
        if(isset($shop_info['shopinfo']['shop_categories'])){
			$query = array(
				'conditions' => array('shopcategories.id' => $shop_info['shopinfo']['shop_categories']), 
				'fields' => array('shopcategories.*'), 
			);
			$shop_categories_info = POP::exe('[@@:UM shopcategories][@@:QU find:first]',$query);	
			
	        if($shop_categories_info['shopcategories']['parent_id'] == 0){
		        $categories_parent = $shop_info['shopinfo']['shop_categories'];
	        } else {
		        $categories_parent = $shop_categories_info['shopcategories']['parent_id'];
		        $categories_child = $shop_info['shopinfo']['shop_categories'];
	        }
        }	
		$query = array(
			'fields' => array('area.*'), 
		);
		$return_array = POP::exe('[@@:UM area][@@:QU find:all]',$query);
	    $areas_info = array();		
	    foreach($return_array as $k=>$v) {
		    $areas_info[$v['area']['area_type']][$v['area']['id']]['id'] = $v['area']['id'];
		    $areas_info[$v['area']['area_type']][$v['area']['id']]['parent_id'] = $v['area']['parent_id'];
		    $areas_info[$v['area']['area_type']][$v['area']['id']]['area_name'] = $v['area']['area_name'];
		    $areas_info[$v['area']['area_type']][$v['area']['id']]['area_type'] = $v['area']['area_type'];
	    }

		$this->set('categories_parent', $categories_parent);	
		$this->set('categories_child', $categories_child);				
		$this->set('shop_info', $shop_info);				
		$this->set('areas_info', $areas_info);	
		$this->set('shop_categories_parent', $shop_categories_parent);
    }	
    //收藏商品,店铺删除
	public function favoritedel() {	
		$user_id = $this->my->id;
		$type= Request::get_args('type');
        if(empty($_POST)){
	        $favorite_id = intval(Request::get_args('id'));
        }else{
	        $favorite=Request::get_args('favorite');
	        if (!$favorite){
		        $this->flash("执行失败！", Router::url('user/favorite/?type='.$type));
	        }
	        $favorite_id=implode(',',$favorite);
        }

		$query = array('conditions'=>array('favorite.user_id' => $user_id,'favorite.id' => $favorite_id));				
        if(POP::exe('[@@:UM favorite][@@:QU del]',$query)) {
	        $this->flash("执行成功！", Router::url('user/favorite/?type='.$type));
        } else {
	        $this->flash("执行失败！", Router::url('user/favorite/?type='.$type));
        }
	
	}
	
	public function favorite() {
		if(!isset(Request::$query['type']))Request::$query['type']='pro';	    
		if(!isset(Request::$query['page']))Request::$query['page']=1;
        $page = intval(Request::$query['page']);
        $type = Request::$query['type'];		
		$user_id = $this->my->id;
		if($type=='pro') {
        /* 我的收藏 */	

		$conditions = array();
		$conditions['favorite.user_id'] = $user_id;	
        $url_this = 'http://'.$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
        $tb = array('model' => 'favorite',
 		            'joins' => array(
					array('type'=>'left','table'=>'goods','conditions'=>array('favorite.goods_id' =>'goods.id')),
					array('type'=>'left','table'=>'shopinfo','conditions'=>array('goods.shop_id' =>'shopinfo.id')),					
					),
				    'fields' => array('shopinfo.user_id','favorite.goods_id','favorite.id','favorite.add_time','goods.shop_id','goods.goods_name','goods.goods_thumb','goods.goods_price','goods.favpv','shopinfo.shop_name','shopinfo.id','shopinfo.lock_flg','shopinfo.open_flg'),
					'conditions' => $conditions,
					'order' => 'favorite.add_time desc',
					'limit' => '10',
					'group' => '',
					'url' => preg_replace("/&page=([^&]+)/","",$url_this),
					'page' => $page,
					'plist' => 6				
				); 
	    $my_favorite = $this->fpage($tb); 
		$this->set('my_favorite', $my_favorite);
		} else if($type=='shop') {
        /* 店铺收藏 */
		$conditions = array();
		$conditions['favorite.user_id'] = $user_id;	
		$conditions['favorite.shop_id <>'] = 0;			
        $url_this = 'http://'.$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
        $tb = array('model' => 'favorite',
 		            'joins' => array(
					array('type'=>'left','table'=>'shopinfo','conditions'=>array('favorite.shop_id' =>'shopinfo.id')),					
					),
				    'fields' => array('shopinfo.id','shopinfo.shop_name','shopinfo.shop_logo','shopinfo.user_id','shopinfo.shop_intro','shopinfo.lock_flg','favorite.id','shopinfo.open_flg','shopinfo.lock_flg'),
					'conditions' => $conditions,
					'order' => 'favorite.add_time desc',
					'limit' => '10',
					'group' => '',
					'url' => preg_replace("/&page=([^&]+)/","",$url_this),
					'page' => $page,
					'plist' => 6				
				); 
		$shop_favorite = $this->fpage($tb); 		
		$this->set('shop_favorite', $shop_favorite);
        }		
		$this->set('type', $type);	
    }	

	public function shopnotice()
    {
	    $this->_teamRights();	
	    if (!empty($this->data)) {
            $safeData = array();			
            $safeData['shopinfo']['shop_notice'] = $this->data['shopinfo']['shop_notice'];		
			$query  = array();	
			$query['keyid'] = $this->data['shop_id'];				
			$query['set'] = $safeData;
			if(POP::exe('[@@:UM shopinfo][@@:QU save]',$query)) {						
				$this->flash("修改成功!", Router::url('user/shopnotice/'));    
			} else {
 				$this->flash("修改失败!", Router::url('user/shopnotice/'));                         
			} 
        }
		$query = array(
			'conditions' => array('shopinfo.user_id' => $this->my->id), 
			'fields' => array('shopinfo.*'), 
		);
		$shop_info = POP::exe('[@@:UM shopinfo][@@:QU find:first]',$query);		

		$this->set('shop_info', $shop_info);
    }	
		
	
	
	public function shoprequest($step='') {
		$query = array(
			'conditions' => array('shoprequest.user_id' => $this->my->id), 
			'fields' => array('shoprequest.*'), 
		);
		$oneuserinfo = POP::exe('[@@:UM shoprequest][@@:QU find:first]',$query);			
		
		$query = array(
			'conditions' => array('shopinfo.user_id' => $this->my->id), 
			'fields' => array('shopinfo.*'), 
		);
		$oneshopinfo = POP::exe('[@@:UM shopinfo][@@:QU find:first]',$query);			
        $errormsg = '';		
        if (!empty($this->data)) {
		    if($this->data['step']==1){ 
			    Loader::import('lib.idcard');
				$idcard = new idcard();
				$idcard->num = $this->data['shoprequest']['credit_num'];
                if(($msg = $idcard->check(18)) || ($msg = $idcard->analyze())) {
					$this->flash("身份证号错误：".$msg, Router::url('user/shoprequest/'));
                }else {								
					if (!empty($_FILES)) {
						$post = array(); 					
						foreach($_FILES as $key=> $value){			
							$upload_name = $key;
							$uploadErrors = array(
								0=>"文件上传成功",
								1=>"上传的文件超过了 php.ini 文件中的 upload_max_filesize directive 里的设置",
								2=>"上传的文件超过了 HTML form 文件中的 MAX_FILE_SIZE directive 里的设置",
								3=>"上传的文件仅为部分文件",
								4=>"没有文件上传",
								6=>"缺少临时文件夹"
							);				
							if (!isset($_FILES[$upload_name])) {
	/* 		                    echo ("没有发现文件 ");
								exit(0); */
								continue;
							} else if (isset($_FILES[$upload_name]["error"][0]) && $_FILES[$upload_name]["error"][0] != 0) {
	/* 		                    echo ($uploadErrors[$_FILES[$upload_name]["error"][0]]);
								exit(0); */
								continue;
							} else if (!isset($_FILES[$upload_name]['name'][0])) {
	/* 		                    echo ("文件无名称");
								exit(0); */
								continue;
							}
							Loader::import('lib.cupload');		
							$up = new upload('jpg|gif|png|jpge',1024, $upload_name);
							$up->set_dir(APP_ROOT . Param::read('upfiles.path') . '/license/','{y}/{m}/{d}');
							$fs=$up->execute();	
							$realtxt=$fs[0];
							$rootpath = trim(str_replace(Param::read('wwwrootPatch'),"",Param::read('htdocPatch')),'/') ;
							$rootpath = !empty($rootpath)?	('/'.$rootpath) : '';						
							if($realtxt['flag']==1){
								$fileSrcStr= $rootpath. str_replace(APP_ROOT,"",$realtxt['dir']).$realtxt['name'];
								$post[$key]['img_url'] = $fileSrcStr;
							}else if($realtxt['flag']==-1||$realtxt['flag']==-2){
								echo ('文件上传关闭');
							}
						}
						isset($post['doc']['img_url']) && !empty($post['doc']['img_url']) && $this->data['shoprequest']['credit_idcard'] = $post['doc']['img_url']; 				
						isset($post['doc1']['img_url']) && !empty($post['doc1']['img_url']) && $this->data['shoprequest']['credit_businesslicense'] = $post['doc1']['img_url']; 
						isset($post['doc2']['img_url']) && !empty($post['doc2']['img_url']) && $this->data['shoprequest']['credit_organizationcode'] = $post['doc2']['img_url']; 
						isset($post['doc3']['img_url']) && !empty($post['doc3']['img_url']) && $this->data['shoprequest']['credit_taxlicense'] = $post['doc3']['img_url'];					
					}

					$query  = array();				
					if(isset($oneuserinfo['shoprequest']['id'])) {	
						$query['keyid'] = $oneuserinfo['shoprequest']['id'];				
						$query['set'] = $this->data;					
					}else {			
						$query = $this->data;		
					}
					if(POP::exe('[@@:UM shoprequest][@@:QU save]',$query)) {				
						$step = 1;				
					} else {
						$step = '';
					} 				
			
			    }
			}else if ($this->data['step']==2) {
				$query = array(
					'conditions' => array('shopinfo.shop_name' => $this->data['shopinfo']['shop_name']), 
					'fields' => array('shopinfo.*'), 
				);
				$tempshopinfo = POP::exe('[@@:UM shopinfo][@@:QU find:first]',$query);			

                if(isset($tempshopinfo['shopinfo']['id'])) {
                    $errormsg = '店铺名有相同的'; 
					 $step = 1;
                }else {
					$this->data['shopinfo']['user_id'] = $this->my->id;
					$this->data['shopinfo']['id'] = $this->my->id;
					!isset($this->data['shopinfo']['categories']) && $this->data['shopinfo']['categories'] =0;
					$this->data['shopinfo']['shop_categories'] =$this->data['shopinfo']['categories'];
					if($this->data['shopinfo']['shop_categories']==0){
						$this->data['shopinfo']['shop_categories'] =$this->data['shopinfo']['categories_parent'];
					}
					unset($this->data['shopinfo']['categories'],$this->data['shopinfo']['categories_parent']);	
					$query  = array();				
					if(isset($oneshopinfo['shopinfo']['id'])) {	
						$query['keyid'] = $oneshopinfo['shopinfo']['id'];				
						$query['set'] = $this->data;					
					}else {			
						$query = $this->data;		
					}
					if(POP::exe('[@@:UM shopinfo][@@:QU save]',$query)) {
						$step = 2;
					} else {
						$step = '';
					}
 
                }				
            }
        }
		if ($step == 1) {
			$query = array(
				'conditions' => array('shopcategories.parent_id' => 0), 
				'fields' => array('shopcategories.*'), 
			);
			$shop_categories_parent = POP::exe('[@@:UM shopcategories][@@:QU find:all]',$query);			
			$query = array(
				'fields' => array('area.*'), 
			);
			$return_array = POP::exe('[@@:UM area][@@:QU find:all]',$query);	

	        $areas_info = array();		
	        foreach($return_array as $k=>$v) {
		        $areas_info[$v['area']['area_type']][$v['area']['id']]['id'] = $v['area']['id'];
		        $areas_info[$v['area']['area_type']][$v['area']['id']]['parent_id'] = $v['area']['parent_id'];
		        $areas_info[$v['area']['area_type']][$v['area']['id']]['area_name'] = $v['area']['area_name'];
		        $areas_info[$v['area']['area_type']][$v['area']['id']]['area_type'] = $v['area']['area_type'];
	        }
		    $this->set('areas_info', $areas_info);	
			$this->set('shop_categories_parent', $shop_categories_parent);
		}
		if($oneuserinfo['shoprequest']['status']==0 && $oneshopinfo['shopinfo']['id']){
		    $step = 2;
		}
		$this->set('oneuserinfo', $oneuserinfo);
		$this->set('errormsg', $errormsg);		
		$this->set('oneshopinfo', $oneshopinfo)	;	
		$this->set('userid', $this->my->id);
		$this->render('shoprequest'.$step);
	}	

	
    function kcaptcha()
    {
        $this->C_captcha->render(); 
    }	

	public function getshopcategories() {	
        $parent_id = intval($_POST['value']);
		$mode = $_POST['mode'];
        isset($_POST['child_value']) && $child_value = intval($_POST['child_value']);		
        if(!$parent_id || empty($mode)) {
	        exit();
        }
        if(!isset($child_value) ||!$child_value) {
	        $child_value=0;
        }
		$query = array(
			'conditions' => array('shopcategories.parent_id' => $parent_id), 
			'fields' => array('shopcategories.*'), 
		);
		$shop_categories = POP::exe('[@@:UM shopcategories][@@:QU find:all]',$query);			
		
        if(!$shop_categories) {
	        exit();
        }	
        $select = '<select name="data['.$mode.'][categories]" >';
        //$select .= '<option value="0">'.$m_langpackage->m_select_province.'</option>';
        foreach($shop_categories as $v) {
	        if($v['shopcategories']['id']==$child_value)
	 	        $select .= '<option value="' . $v['shopcategories']['id'] . '" selected >' . $v['shopcategories']['cat_name']. '</option>';
	        else
	 	        $select .= '<option value="' . $v['shopcategories']['id'] . '">' . $v['shopcategories']['cat_name'] . '</option>';
        }
        $select .= '</select>';
        echo $select;		
		exit;

	}		
	public function getareas() {
	
        $parent_id = intval($_POST['value']);
        $type = intval($_POST['type']);
        $mode = $_POST['mode'];
        $pre = $_POST['pre'];		
        if(!$parent_id) {
	        exit();
        }
        if($type<0 || $type>3 || empty($mode)) {
	        exit();
        }	
		
		$query = array(
			'conditions' => array('area.parent_id' => $parent_id), 
			'fields' => array('area.*'), 
		);
		$areas_info = POP::exe('[@@:UM area][@@:QU find:all]',$query);			
		
        header('Content-Type: text/html; charset='.Param::read('App.encoding'));		
        $select = "";
        if($type==0) {
	        $select .= '<select name="data['.$mode.']['.$pre.'province]"   onchange="areachanged(this.value,1);">';
	        $select .= '<option value="0">请选择省份...</option>';
        } elseif($type==1) {
	        $select .= '<select name="data['.$mode.']['.$pre.'city]"   onchange="areachanged(this.value,2);">';
	        $select .= '<option value="0">请选择城市...</option>';
        } elseif($type==2) {
	        $select .= '<select name="data['.$mode.']['.$pre.'district]"  onchange="areachanged(this.value,3);">';
	        $select .= '<option value="0">请选择区域...</option>';
        } elseif($type==3) {
	        $select .= '<select name="data['.$mode.']['.$pre.'bcircle]">';
	        $select .= '<option value="0">请选择商圈...</option>';
        }
		
        foreach($areas_info as $v) {
	        $select .= '<option value="' . $v['area']['id'] . '">' . $v['area']['area_name'] . '</option>';
        } 
        $select .= '</select>';
        echo $select;
		exit;

	}
	
    //收货地址
	public function deladdress() {	
        $address_id=intval(Request::get_args('address_id'));	
		$query = array(
			'conditions' => array('useraddress.user_id' => $this->my->id,'useraddress.id' => $address_id), 
			'fields' => array('useraddress.*'), 
		);
		$address_rs = POP::exe('[@@:UM useraddress][@@:QU find:first]',$query);			

		if(empty($address_rs)) {
            $this->flash("该项不存在!", Router::url('user/address/'));		
		}else {
		    $this->useraddress->delete($address_id);
            $this->flash("执行成功！", Router::url('user/address/'));		   
		}        		
	}
	
    //收货地址
	public function address() {	
        $address_id=intval(Request::get_args('address_id'));		
        if(!empty($this->data)) {
            if($this->data['useraddress']['id']) {		
                $this->useraddress->id = $this->data['useraddress']['id'];
				$address_id = $this->data['useraddress']['id'];
			}
			unset($this->data['useraddress']['id']);
			$this->data['useraddress']['user_id'] = $this->my->id;
			$safeData = $this->data['useraddress'];
		    $this->useraddress->set( $safeData );
		    $this->useraddress->save($safeData);
			
        }
		$query = array(
			'conditions' => array('useraddress.user_id' => $this->my->id), 
			'fields' => array('useraddress.*'), 
		);
		$address_rs = POP::exe('[@@:UM useraddress][@@:QU find:all]',$query);	
		
        $user_info=array(
	        'user_country'=>'',
	        'user_id'=>'',
	        'user_province'=>'',
	        'user_city'=>'',
	        'to_user_name'=>'',
	        'user_district'=>'',
	        'full_address'=>'',
	        'zipcode'=>'',
	        'mobile'=>'',
	        'telphone'=>'',
	        'email'=>'',
        );
        if($address_id && $address_rs){
	        foreach($address_rs as $value) {
		        if($address_id == $value['useraddress']['id']) {
			        $user_info = $value['useraddress'];
		        }
	        }
        }
        // 用户所选国家， 如果没选默认为1（中国）
        $user_info['user_country'] = $user_info['user_country'] ? $user_info['user_country'] : 1;	
		$query = array(
			'fields' => array('area.*'), 
		);
		$return_array = POP::exe('[@@:UM area][@@:QU find:all]',$query);	

	    $areas_info = array();		
	    foreach($return_array as $k=>$v) {
		    $areas_info[$v['area']['area_type']][$v['area']['id']]['id'] = $v['area']['id'];
		    $areas_info[$v['area']['area_type']][$v['area']['id']]['parent_id'] = $v['area']['parent_id'];
		    $areas_info[$v['area']['area_type']][$v['area']['id']]['area_name'] = $v['area']['area_name'];
		    $areas_info[$v['area']['area_type']][$v['area']['id']]['area_type'] = $v['area']['area_type'];
	    }	
        $this->set('areas_info',$areas_info);		
        $this->set('user_info',$user_info);		
        $this->set('address_rs',$address_rs);	
        $this->set('address_id',$address_id);
	}
	
	public function buyorderadress() {	
        $gid = Request::get_args("gid");
		$goods_id = $gid;
        $order_num = Request::get_args("v");
        isset($_GET['address_id'])? $address_id = intval($_GET['address_id']) : $address_id = 0;
		if(!$goods_id) { exit("非法操作"); }
        if(!$order_num) { exit("非法操作"); }
        if(!is_array($goods_id)){
	        $goods_id=array(intval($goods_id));
        }
        if(!is_array($order_num)){
	        $order_num=array(intval($order_num));
        }
        $url_param ="";
        for($i=0; $i< sizeof($goods_id);$i++)
        {
	        $url_param.="&gid[]=".$goods_id[$i]."&v[]=".$order_num[$i];
        } 
        /* 产品信息获取 */
        $as=implode(",",$goods_id);
		$query = array(
			'conditions' => array('goods.id' => $goods_id,'goods.is_on_sale'=>1), 
			'fields' => array('goods.*'), 
		);
		$goodsinfo = POP::exe('[@@:UM goods][@@:QU find:first]',$query);			
	
        if($goodsinfo['goods']['goods_number']==0) { exit('库存为0，您暂时无法购买！'); }
        if($goodsinfo['goods']['lock_flg']) { exit('此商品已被锁定'); }
        if(!$goodsinfo) { exit('没有此商品'); }
        if($goodsinfo['goods']['goods_price']=='0.00'){
	        //echo "<script language='JavaScript'>location.href='inquiry.php?gid=$goods_id[0]'</script>";
		    $this->flash("产品价格为0,不能购买！", Request::referer());
        }else {
		
		$query = array(
			'conditions' => array('useraddress.user_id' => $this->my->id), 
			'fields' => array('useraddress.*'), 
		);
		$address_rs = POP::exe('[@@:UM useraddress][@@:QU find:all]',$query);		
		
        $user_info=array(
	        'user_country'=>'',
	        'user_id'=>'',
	        'user_province'=>'',
	        'user_city'=>'',
	        'to_user_name'=>'',
	        'user_district'=>'',
	        'full_address'=>'',
	        'zipcode'=>'',
	        'mobile'=>'',
	        'telphone'=>'',
	        'email'=>'',
        );
        if($address_id && $address_rs){
	        foreach($address_rs as $value) {
		        if($address_id == $value['useraddress']['id']) {
			        $user_info = $value['useraddress'];
		        }
	        }
        } elseif ($address_rs) {
	        $user_info = $address_rs[0]['useraddress'];
	        $address_id = $address_rs[0]['useraddress']['id'];
        }
        $tablestyle="none";
        if(!$address_rs){
	        $tablestyle="block";
        }		

        $shop_id=$this->my->id;
        if(is_array($goods_id)){
			$query = array(
				'conditions' => array('goods.id' => $goods_id[0]), 
				'fields' => array('goods.*'), 
			);
			$goods_info = POP::exe('[@@:UM goods][@@:QU find:first]',$query);		
        }else{
			$query = array(
				'conditions' => array('goods.id' => $goods_id), 
				'fields' => array('goods.*'), 
			);
			$goods_info = POP::exe('[@@:UM goods][@@:QU find:first]',$query);			
        }		
        if($shop_id == $goods_info['goods']['id']) {
	        exit('不能购买自己的商品！');
        }		
        if(!$goods_info) { exit("非法操作"); }		
        $user_info['user_id'] = $this->my->id;
        // 用户所选国家， 如果没选默认为1（中国）
        $user_info['user_country'] = $user_info['user_country'] ? $user_info['user_country'] : 1;		
		

		$query = array(
			'fields' => array('area.*'), 
		);
		$return_array = POP::exe('[@@:UM area][@@:QU find:all]',$query);			
		
		
	    $areas_info = array();		
	    foreach($return_array as $k=>$v) {
		    $areas_info[$v['area']['area_type']][$v['area']['id']]['id'] = $v['area']['id'];
		    $areas_info[$v['area']['area_type']][$v['area']['id']]['parent_id'] = $v['area']['parent_id'];
		    $areas_info[$v['area']['area_type']][$v['area']['id']]['area_name'] = $v['area']['area_name'];
		    $areas_info[$v['area']['area_type']][$v['area']['id']]['area_type'] = $v['area']['area_type'];
	    }	

		$query = array(
			'conditions' => array('userlogistics.user_id' => $this->my->id), 
			'fields' => array('userlogistics.*'), 
		);
		$my_address_rs = POP::exe('[@@:UM userlogistics][@@:QU find:all]',$query);				
		
		$query = array(
			'conditions' => array('userlogistics.user_id' => $goods_info['goods']['shop_id']), 
			'fields' => array('userlogistics.*'), 
		);
		$shop_address_rs = POP::exe('[@@:UM userlogistics][@@:QU find:all]',$query);

        $this->set('my_address_rs',$my_address_rs);		
        $this->set('shop_address_rs',$shop_address_rs);	

		
		$query = array(
			'conditions' => array('shoppayment.shop_id' => $goods_info['goods']['shop_id']), 
			'fields' => array('shoppayment.*'), 
		);
		$payment_info = POP::exe('[@@:UM shoppayment][@@:QU find:all]',$query);		

		$query = array(
			'fields' => array('payment.*'), 
		);
		$array = POP::exe('[@@:UM payment][@@:QU find:all]',$query);			
		
	    $payment = array();
	    foreach($array as $value) {
		    $payment[$value['payment']['id']] = $value['payment']['pay_name'];
	    }		
        $newaddress="";
        if(!empty($address_rs)){
	         $newaddress="display:none";
        }
        $this->set('order_num',$order_num);
        $this->set('goods_id',$goods_id);		
        $this->set('areas_info',$areas_info);		
        $this->set('user_info',$user_info);		
        $this->set('address_rs',$address_rs);		
        $this->set('newaddress',$newaddress);
        $this->set('goods_info',$goods_info);		
        $this->set('address_id',$address_id);
        $this->set('url_param',$url_param);		
        $this->set('payment',$payment);	
        $this->set('payment_info',$payment_info);
        }		
		
	}	

	public function userorder() {
        $address_id = intval($_POST['address_id']);
        isset($this->data['payid'])?$pay_id = intval($this->data['payid']):$pay_id = '';		
        $goods_id = $_GET['gid'];
		$goods_id=explode(",",$goods_id);
        if(is_array($goods_id)){
	        foreach ($goods_id as $k=>$v){
		        $goods_id[$k]=intval($v);
	        }
        }else{
	        $goods_id=array(intval($goods_id));
        }		
        $order_num = $_GET['v'];
        $order_num = explode(",",$order_num);
        if(is_array($order_num)){
	        foreach ($order_num as $k=>$v){
		        $order_num[$k]=intval($v);
	        }
        }else{
	        $order_num=array(intval($order_num));
        }
        foreach ($goods_id as $k=>$v){
	        $buy_goods[$v]=$order_num[$k];
        }		
        if(!$goods_id) { exit('非法操作！'); }
        if(!$order_num) { exit('非法操作！'); }
		$query = array(
			'conditions' => array('useraddress.user_id' => $this->my->id), 
			'fields' => array('useraddress.*'), 
		);
		$address_rs = POP::exe('[@@:UM useraddress][@@:QU find:all]',$query);		

        $ntablestyle="display:none";
        if(!$address_rs){
            $ntablestyle="display:block";
        }		
        $user_info=array(
	        'user_country'=>'',
	        'user_id'=>'',
	        'user_province'=>'',
	        'user_city'=>'',
	        'to_user_name'=>'',
	        'user_district'=>'',
	        'full_address'=>'',
	        'zipcode'=>'',
	        'mobile'=>'',
	        'telphone'=>'',
	        'email'=>'',
        );
        foreach($this->data['useraddress'] as $k =>$v) {
            $user_info[$k]=$v;
        }		
        if(isset($this->data['issave'])&&$this->data['issave']=='1'){
		    $this->data['useraddress']['user_id'] = $this->my->id;
            $safedata = $this->data;								
			POP::exe('[@@:UM useraddress][@@:QU save]',$safedata);				

        }
        // 用户所选国家， 如果没选默认为1（中国）
        $user_info['user_country'] = !empty($user_info['user_country']) ? $user_info['user_country'] : 1;		
		//查询商品库存
        $goods_info = array();
		$query = array(
			'conditions' => array('goods.id' => $goods_id), 
			'fields' => array('goods.*'), 
		);
		$rs = POP::exe('[@@:UM goods][@@:QU find:all]',$query);		
   
	    $arr=array();
        foreach ($rs as $k=>$v){
	        $arr[$v['goods']['id']]=$v['goods']['goods_number'];
        }
        foreach ($buy_goods as $k=>$v){
	        if ($arr[$k]>=$v) {
				$query = array(
					'conditions' => array('goods.id' => $k), 
					'fields' => array('goods.*'), 
				);
				$ttemp = POP::exe('[@@:UM goods][@@:QU find:first]',$query);				
		        $goods_info[]=$ttemp['goods'];
	        }
        }	   
	    if(!$goods_info) { exit('非法操作！'); }
	    $shop_id=$this->my->id;
        if($shop_id == $goods_info[0]['shop_id']) {
	         exit('不能购买自己的商品！');
        }	   
	    $user_info['user_id'] = $this->my->id;
	    $user_info['logistics_content'] = Request::get_args('logistics_content');		
	    $user_info['logistics_money'] = Request::get_args('logistics_money');		
		
		$query = array(
			'fields' => array('area.*'), 
		);
		$return_array = POP::exe('[@@:UM area][@@:QU find:all]',$query);	
		
	    $areas_info = array();		
	    foreach($return_array as $k=>$v) {
		    $areas_info[$v['area']['area_type']][$v['area']['id']]['id'] = $v['area']['id'];
		    $areas_info[$v['area']['area_type']][$v['area']['id']]['parent_id'] = $v['area']['parent_id'];
		    $areas_info[$v['area']['area_type']][$v['area']['id']]['area_name'] = $v['area']['area_name'];
		    $areas_info[$v['area']['area_type']][$v['area']['id']]['area_type'] = $v['area']['area_type'];
	    }			
		
		$query = array(
			'conditions' => array('shopcustomer.user_name' => $this->my->username,'shopcustomer.shop_id'=>$goods_info[0]['shop_id']), 
			'fields' => array('shopcustomer.*'), 
		);
		$customer = POP::exe('[@@:UM shopcustomer][@@:QU find:first]',$query);			
		
		$query = array(
			'conditions' => array('shopcustomcat.shop_id' => $goods_info[0]['shop_id'],'shopcustomcat.id' => $customer['shopcustomer']['customcat_id']), 
			'fields' => array('shopcustomcat.*'), 
		);
		$customer_cat = POP::exe('[@@:UM shopcustomcat][@@:QU find:first]',$query);	
	
        $this->set('customer_cat',$customer_cat);		

		$query = array(
			'conditions' => array('shoppayment.shop_id' => $goods_info[0]['shop_id'],'shoppayment.pay_id'=>$pay_id), 
			'fields' => array('shoppayment.*'), 
		);
		$payment_info = POP::exe('[@@:UM shoppayment][@@:QU find:first]',$query);			

		$query = array(
			'fields' => array('payment.*'), 
		);
		$array = POP::exe('[@@:UM payment][@@:QU find:all]',$query);		

	    $payment = array();
	    foreach($array as $value) {
		    $payment[$value['payment']['id']] = $value['payment']['pay_name'];
	    }	
        $this->set('order_num',$order_num);
        $this->set('goods_id',$goods_id);				
        $this->set('user_info',$user_info);		
        $this->set('address_rs',$address_rs);		
        $this->set('goods_info',$goods_info);		
        $this->set('address_id',$address_id);
        $this->set('areas_info',$areas_info);	
        $this->set('buy_goods',$buy_goods);	
        $this->set('payment',$payment);	
        $this->set('payment_info',$payment_info);	
	}

	public function userdoorder() {
	    $post['shop_id'] = $this->data['sshop_id'];
        $post['user_id'] = $this->my->id;
        $goods_id = $this->data['goods_id'];
        if (is_array($goods_id)) {
	        foreach ($goods_id as $k=>$v){
		        $goods_id[$k]=intval($v);
	        }
        }else{
	        $goods_id=array(intval($goods_id));
        }
        $post['pay_id'] = intval($this->data['pay_id']);
        $post['pay_name'] = $this->data['pay_name'];
        $goods_name=$this->data['goods_name'];
        $goods_price = $this->data['goods_price'];	
        if (is_array($goods_price)) {
	        foreach ($goods_price as $k=>$v){
		        $goods_price[$k]=floatval($v);
	        }
        }else{
	        $goods_price=array(floatval($goods_price));
        }	
        $goods_old_price = $this->data['goods_old_price'];	
        if (is_array($goods_old_price)) {
	        foreach ($goods_old_price as $k=>$v){
		        $goods_old_price[$k]=floatval($v);
	        }
        }else{
	        $goods_old_price=array(floatval($goods_old_price));
        }		
		
        $transport_type = '';
        if($transport_type){
	        $aa=explode(',',$transport_type);
	        $post['transport_price'] = floatval($aa[0]);
	        $post['transport_type'] = $aa[1];
        }else {
            $post['transport_price'] = floatval($this->data['transportmoney']);
        }
        $order_amount = $this->data["order_amount"];
        if (is_array($order_amount)) {
	        foreach ($order_amount as $k=>$v){
		        $order_amount[$k]=floatval($v);
	        }
        }else{
	        $order_amount=array(floatval($order_amount));
        }
        $order_amount_value=0;
        foreach ($order_amount as $value){
	        $order_amount_value+=$value;
        }
        $post['order_amount'] =$order_amount_value;
        $post['order_value'] = $order_amount_value+floatval($post['transport_price']);
        $order_num = $this->data["order_num"];
        if (is_array($order_num)) {
	        foreach ($order_num as $k=>$v){
		        $order_num[$k]=intval($v);
	        }
        }else{
	        $order_num =array(intval($order_num));
        }
        $post['consignee'] = $this->data['to_user_name'];
        $post['country'] = intval($this->data['country']);
        $post['province'] = intval($this->data['province']);
        $post['city'] = intval($this->data['city']);
        $post['district'] = intval($this->data['district']);
        $post['mobile'] = $this->data['mobile'];
        $post['email'] = $this->data['email'];
        $post['telphone'] = $this->data['telphone'];
        $post['zipcode'] = $this->data['zipcode'];
        $post['address'] = $this->data['full_address'];
        $post['message'] = $this->data['message'];
        $post['transport_content'] = Request::get_args('transportcontent');
        $post['rebatemoney'] = Request::get_args('rebatemoney');		
        $post['order_time'] = date("Y-m-d H:i:s",time());
        $rand = rand(10,99);
        $post['payid'] = date("YmdHis".$rand);
        $quantity = $this->data['order_num'];
        if (is_array($quantity)) {
	        foreach ($quantity as $k=>$v){
		       $quantity[$k]=intval($v);
	        }
        }else{
	        $quantity =array(intval($quantity));
        }
        if (is_array($goods_name)) {
	        foreach ($goods_name as $k=>$v){
		        $goods_name[$k]=$v;
	        }
        }else{
	        $goods_name =array($goods_name);
        }	
		$query = array(
			'conditions' => array('cart.goods_id' => $goods_id,'cart.user_id' => $post['user_id']), 
			'fields' => array('cart.*'), 
		);
		$cat_rs = POP::exe('[@@:UM cart][@@:QU find:first]',$query);
	
        /** 检查商品数量 */
        foreach ($goods_id as $k=>$v){
			$query = array(
				'conditions' => array('goods.id' => $v), 
				'fields' => array('goods.*'), 
			);
			$goods_info = POP::exe('[@@:UM goods][@@:QU find:first]',$query);		
	
	        if($quantity[$k]>$goods_info['goods']['goods_number']){
                exit('库存不足，请和店主联系');
	        }
        }
		$update_items=array();
		$update_items['orderinfo']=$post;
        //生成订单
        $err_no=0;		
        $order_id = POP::exe('[@@:UM orderinfo][@@:QU save]',$update_items);		
        if ($order_id) {
		    $this->loadModel('credit');
		    $this->loadModel('ordergoods');			
	        foreach ($goods_id as $k=>$v){
                $temp = array();
                $temp['credit']['order_id']=$order_id;
                $temp['credit']['goods_id']= $v;
                $temp['credit']['buyer']= $this->my->id;	
                $temp['credit']['seller']= $post['shop_id'];
                POP::exe('[@@:UM credit][@@:QU save]',$temp);				
		        $info = array(
			        "order_id"=>$order_id,
			        "goods_id"=>$v,
			        "goods_name"=>$goods_name[$k],
			        "goods_price"=>$goods_price[$k],
			        "goods_old_price"=>$goods_old_price[$k],					
			        "order_num"=>$order_num[$k],
		            "shop_id"=>$post['shop_id'],
			        "good_tran"=>$post['transport_price'],
			        "add_time"=>date("Y-m-d H:i:s",time())
		        );
				$temp = array();
				$temp['ordergoods'] = $info ;				
		        if(!POP::exe('[@@:UM ordergoods][@@:QU save]',$temp)){
			        $err_no[]=$v;
		        }else{           
			        if ($cat_rs){
						$query = array('conditions'=>array('cart.user_id' => $this->my->id,'cart.goods_id' => $v));				
						POP::exe('[@@:UM cart][@@:QU del]',$query);						
						$car=$this->C_session->read('_user_temp.cart');
				        if($car){
					        if(isset($car[$v])){
						        unset($car[$v]);
					        }
					        $this->C_session->write('_user_temp.cart', $car);
				        }
				        /** 减少库存 */
						$query  = array();		
						$query['keyid'] = true;
						$safeData['goods'] = array('goods_number -'=>$quantity[$k]);				
						$query['set'] = $safeData;	
						$query['conditions'] = array('goods.id'=>$v);		
						POP::exe('[@@:UM goods][@@:QU save]',$query);						
			        }else {
						$query  = array();		
						$query['keyid'] = true;
						$safeData['goods'] = array('goods_number -'=>$quantity[$k]);				
						$query['set'] = $safeData;	
						$query['conditions'] = array('goods.id'=>$v);		
						POP::exe('[@@:UM goods][@@:QU save]',$query);
			        }
		        }
	        }
        }else{
	        $err_no="-1";
        }
        if ($err_no==0) {		    
			$this->flash("订单成功", Router::url('user/userordersuccess/?id='.$post['payid']).'&orderid='.$order_id);
        }else{
			$this->flash('订单失败', '-1');
        }		
    }	

	public function userorderdel() {	
        $order_id = intval($_GET['id']);
		if(!$order_id) { exit('非法操作！'); }
		$user_id = $this->my->id;
        //判断商品是否锁定，锁定则不许操作

		$query = array(
				'joins' => array(
					array('type'=>'left','table'=>'ordergoods','conditions'=>array('orderinfo.id' =>'ordergoods.order_id')),					
					),
				'fields' => array('ordergoods.goods_id'),
				'conditions' => array('orderinfo.id' =>$order_id),
				'group' => ''
				);	
	    $row = POP::exe('[@@:UM orderinfo][@@:QU find:all]',$query);
		
        if($row){
		    $rows = array();
		    foreach($row as $k => $v) {
                $rows[$v['b']['goods_id']] = $v['b']['goods_id'];
            }			
	        $goods_id = $rows;
        }
		$query = array(
			'conditions' => array('goods.id' => $goods_id), 
			'fields' => array('goods.*'), 
		);
		$goods = POP::exe('[@@:UM goods][@@:QU find:all]',$query);		

        foreach($goods_id as $vid) {
		    $istrue = array();
            foreach($goods as $v) {
                if($v['goods']['id'] == $vid){
				    $istrue = $v['goods'];
					break;
				} 			
            }
			if(empty($istrue)) { exit( "该订单中有商品不存在");}//没有此商品
        } 	
        foreach($goods as $v) {
            if($v['goods']['lock_flg'] == 1){
				exit('['.$v['goods']['goods_name']."]商品已被锁定");
			}				
        }
        if($this->my->locked==1){
	        $this->C_session->destroy();
	        exit("您已经被锁定了");//非法操作
        }
		$order_info = array();
		$query = array(
			'conditions' => array('orderinfo.id' => $order_id,'orderinfo.user_id' => $user_id), 
			'fields' => array('orderinfo.*'), 
		);
		$order_info = POP::exe('[@@:UM orderinfo][@@:QU find:first]',$query);	
		if(!$order_info ) { exit('该订单不存在！');  }
		$order_info = $order_info['orderinfo'];

		$query = array(
				'joins' => array(
					array('type'=>'left','table'=>'shopinfo','conditions'=>array('shopinfo.id' =>'goods.shop_id')),				
					array('type'=>'left','table'=>'ordergoods','conditions'=>array('ordergoods.goods_id' =>'goods.id')),					
					),
				'fields' => array('ordergoods.goods_id','ordergoods.goods_price','ordergoods.order_num','ordergoods.goods_name','ordergoods.id','goods.goods_thumb','shopinfo.user_id','shopinfo.shop_name'),
				'conditions' => array('ordergoods.order_id' =>$order_info['id'],'shopinfo.id' =>$order_info['shop_id']),
				);	
	    $list = POP::exe('[@@:UM goods][@@:QU find:all]',$query);		
		
		
	    $order_info['order_goods']=$list;
		
        if($order_info['order_status']=='0') {
	        exit("订单状态异常");
        } elseif ($order_info['order_status']=='3') {
	        exit("此订单已完成不能取消");
        }elseif ($order_info['order_status']=='2') {
	        exit("该订单卖家已经确认,您不能取消订单！");
        }
		$query  = array();		
		$query['keyid'] = true;
		$safeData['orderinfo'] = array('order_status'=>0);				
		$query['set'] = $safeData;	
		$query['conditions'] = array('orderinfo.id'=>$order_id,'orderinfo.user_id'=>$user_id);
        if(POP::exe('[@@:UM orderinfo][@@:QU save]',$query)) {			
			$this->flash("此订单已成功取消", Router::url('user/usermyorder/'));
        } else {
			$this->flash("此订单取消失败", '-1');
        }	
	}
	
	public function surebackmoney() {
        $order_id = intval($_GET['id']);
		if(!$order_id) { exit('非法操作！'); }
		$user_id = $this->my->id;
        //判断商品是否锁定，锁定则不许操作
		$query = array(
				'joins' => array(
					array('type'=>'left','table'=>'ordergoods','conditions'=>array('orderinfo.id' =>'ordergoods.order_id')),					
					),
				'fields' => array('ordergoods.goods_id'),
				'conditions' => array('orderinfo.id' =>$order_id),
				'group' => ''
				);	
	    $row = POP::exe('[@@:UM orderinfo][@@:QU find:all]',$query);
		
        if($row){
		    $rows = array();
		    foreach($row as $k => $v) {
                $rows[$v['b']['goods_id']] = $v['b']['goods_id'];
            }			
	        $goods_id = $rows;
        }
		$query = array(
			'conditions' => array('goods.id' => $goods_id), 
			'fields' => array('goods.*'), 
		);
		$goods = POP::exe('[@@:UM goods][@@:QU find:all]',$query);			

        foreach($goods_id as $vid) {
		    $istrue = array();
            foreach($goods as $v) {
                if($v['goods']['id'] == $vid){
				    $istrue = $v['goods'];
					break;
				} 			
            }
			if(empty($istrue)) { exit( "该订单中有商品不存在");}//没有此商品
        } 	
        foreach($goods as $v) {
            if($v['goods']['lock_flg'] == 1){
				exit('['.$v['goods']['goods_name']."]商品已被锁定");
			}				
        }
        if($this->my->locked==1){
	        $this->C_session->destroy();
	        exit("您已经被锁定了");//非法操作
        }		
		$order_info = array();
		$query = array(
			'conditions' => array('orderinfo.id' => $order_id,'orderinfo.user_id' => $user_id), 
			'fields' => array('orderinfo.*'), 
		);
		$order_info = POP::exe('[@@:UM orderinfo][@@:QU find:first]',$query);		
		if(!$order_info ) { exit('该订单不存在！');  }
		$order_info = $order_info['orderinfo'];

		$query = array(
				'joins' => array(
					array('type'=>'left','table'=>'shopinfo','conditions'=>array('shopinfo.id' =>'goods.shop_id')),				
					array('type'=>'left','table'=>'ordergoods','conditions'=>array('ordergoods.goods_id' =>'goods.id')),					
					),
				'fields' => array('ordergoods.goods_id','ordergoods.goods_price','ordergoods.order_num','ordergoods.goods_name','ordergoods.id','goods.goods_thumb','shopinfo.user_id','shopinfo.shop_name'),
				'conditions' => array('ordergoods.order_id' =>$order_info['id'],'shopinfo.id' =>$order_info['shop_id']),
				);	
	    $list = POP::exe('[@@:UM goods][@@:QU find:all]',$query);		
		
	    $order_info['order_goods']=$list;		
        //判断订单状态，锁定则不许操作
        if($order_info['order_status']=='0') {
	        exit("订单状态异常");
        } elseif ($order_info['order_status']=='3') {
	        exit("此订单已完成不能取消");
        }
        //判断支付状态，锁定则不许操作
        if ($order_info['pay_status']!='3') {
	        exit("商家还未确认退款！");
        }
        //数据库操作
		$query  = array();		
		$query['keyid'] = true;
		$safeData['orderinfo'] = array('pay_status'=>4);				
		$query['set'] = $safeData;	
		$query['conditions'] = array('orderinfo.id'=>$order_id,'orderinfo.user_id'=>$user_id);
        if(POP::exe('[@@:UM orderinfo][@@:QU save]',$query)) {		
	        exit("已经退款成功！");
        }else {
	        exit("已经退款失败！");
        }		
	}	
	
	public function usercancelprotect() {
        $order_id = intval($_GET['order_id']);
		if(!$order_id) { exit('非法操作！'); }
		$user_id = $this->my->id;
        //判断商品是否锁定，锁定则不许操作
		$query = array(
				'joins' => array(
					array('type'=>'left','table'=>'ordergoods','conditions'=>array('orderinfo.id' =>'ordergoods.order_id')),					
					),
				'fields' => array('ordergoods.goods_id','orderinfo.transport_type'),
				'conditions' => array('orderinfo.id' =>$order_id),
				'group' => ''
				);	
	    $row = POP::exe('[@@:UM orderinfo][@@:QU find:all]',$query);
		
        if($row){
		    $rows = array();
		    foreach($row as $k => $v) {
                $rows[$v['b']['goods_id']] = $v['b']['goods_id'];
            }			
	        $goods_id = $rows;
        }
		$query = array(
			'conditions' => array('goods.id' => $goods_id), 
			'fields' => array('goods.*'), 
		);
		$goods = POP::exe('[@@:UM goods][@@:QU find:all]',$query);			

        foreach($goods_id as $vid) {
		    $istrue = array();
            foreach($goods as $v) {
                if($v['goods']['id'] == $vid){
				    $istrue = $v['goods'];
					break;
				} 			
            }
			if(empty($istrue)) { exit( "该订单中有商品不存在");}//没有此商品
        } 	
        foreach($goods as $v) {
            if($v['goods']['lock_flg'] == 1){
				exit('['.$v['goods']['goods_name']."]商品已被锁定");
			}				
        }
        if($this->my->locked==1){
	        $this->C_session->destroy();
	        exit("您已经被锁定了");//非法操作
        }
		$order_info = array();
		$query = array(
			'conditions' => array('orderinfo.id' => $order_id,'orderinfo.user_id' => $user_id), 
			'fields' => array('orderinfo.*'), 
		);
		$order_info = POP::exe('[@@:UM orderinfo][@@:QU find:first]',$query);		
		
		if(!$order_info ) { exit('该订单不存在！');  }
		$order_info = $order_info['orderinfo'];
		
		$query = array(
				'joins' => array(
					array('type'=>'left','table'=>'shopinfo','conditions'=>array('shopinfo.id' =>'goods.shop_id')),				
					array('type'=>'left','table'=>'ordergoods','conditions'=>array('ordergoods.goods_id' =>'goods.id')),					
					),
				'fields' => array('ordergoods.goods_id','ordergoods.goods_price','ordergoods.order_num','ordergoods.goods_name','ordergoods.id','goods.goods_thumb','shopinfo.user_id','shopinfo.shop_name'),
				'conditions' => array('ordergoods.order_id' =>$order_info['id'],'shopinfo.id' =>$order_info['shop_id']),
				);	
	    $list = POP::exe('[@@:UM goods][@@:QU find:all]',$query);		
		
	    $order_info['order_goods']=$list;	
        //判断订单状态，锁定则不许操作
        if($order_info['order_status']=='0') {
			exit("订单状态异常");
        } elseif ($order_info['order_status']!='3') {
			exit("该订单还未确定收货!");
        }elseif ($order_info['protect_status']=='0') {
			exit("没申请维权！");
        }elseif ($order_info['protect_status']=='3') {
			exit("维权已经结束！");
        }        
		$query  = array();		
		$query['keyid'] = true;
		$safeData['orderinfo'] = array('protect_status'=>3);				
		$query['set'] = $safeData;	
		$query['conditions'] = array('orderinfo.id'=>$order_id,'orderinfo.user_id'=>$user_id);
        if(POP::exe('[@@:UM orderinfo][@@:QU save]',$query)) {
			$this->flash("结束维权成功！", Router::url('user/usermyorder/'));
        } else {
			$this->flash("结束维权失败！",'-1');
        }	
	
    }	
	
	public function userprotectrights() {
        $order_id = intval($_GET['order_id']);
		if(!$order_id) { exit('非法操作！'); }
		$user_id = $this->my->id;
        //判断商品是否锁定，锁定则不许操作
		$query = array(
				'joins' => array(
					array('type'=>'left','table'=>'ordergoods','conditions'=>array('orderinfo.id' =>'ordergoods.order_id')),					
					),
				'fields' => array('ordergoods.goods_id','orderinfo.transport_type'),
				'conditions' => array('orderinfo.id' =>$order_id),
				'group' => ''
				);	
	    $row = POP::exe('[@@:UM orderinfo][@@:QU find:all]',$query);
		
        if($row){
		    $rows = array();
		    foreach($row as $k => $v) {
                $rows[$v['b']['goods_id']] = $v['b']['goods_id'];
            }			
	        $goods_id = $rows;
        }
		$query = array(
			'conditions' => array('goods.id' => $goods_id), 
			'fields' => array('goods.*'), 
		);
		$goods = POP::exe('[@@:UM goods][@@:QU find:all]',$query);			

        foreach($goods_id as $vid) {
		    $istrue = array();
            foreach($goods as $v) {
                if($v['goods']['id'] == $vid){
				    $istrue = $v['goods'];
					break;
				} 			
            }
			if(empty($istrue)) { exit( "该订单中有商品不存在");}//没有此商品
        } 	
        foreach($goods as $v) {
            if($v['goods']['lock_flg'] == 1){
				exit('['.$v['goods']['goods_name']."]商品已被锁定");
			}				
        }
        if($this->my->locked==1){
	        $this->C_session->destroy();
	        exit("您已经被锁定了");//非法操作
        }
		$order_info = array();
		$query = array(
			'conditions' => array('orderinfo.id' => $order_id,'orderinfo.user_id' => $user_id), 
			'fields' => array('orderinfo.*'), 
		);
		$order_info = POP::exe('[@@:UM orderinfo][@@:QU find:first]',$query);		
	
		if(!$order_info ) { exit('该订单不存在！');  }
		$order_info = $order_info['orderinfo'];
		$query = array(
				'joins' => array(
					array('type'=>'left','table'=>'shopinfo','conditions'=>array('shopinfo.id' =>'goods.shop_id')),				
					array('type'=>'left','table'=>'ordergoods','conditions'=>array('ordergoods.goods_id' =>'goods.id')),					
					),
				'fields' => array('ordergoods.goods_id','ordergoods.goods_price','ordergoods.order_num','ordergoods.goods_name','ordergoods.id','goods.goods_thumb','shopinfo.user_id','shopinfo.shop_name'),
				'conditions' => array('ordergoods.order_id' =>$order_info['id'],'shopinfo.id' =>$order_info['shop_id']),
				);	
	    $list = POP::exe('[@@:UM goods][@@:QU find:all]',$query);		
		
	    $order_info['order_goods']=$list;	
        
        //判断订单状态，锁定则不许操作
        if($order_info['order_status']=='0') {
	        exit("订单状态异常");
        } elseif ($order_info['order_status']!='3') {
	       exit('该订单还未确定收货!');
        }
		if(!empty($this->data)) {
            $protect_content = $this->data['protect_content'];
            $protect_item = $this->data['protect_item'];
            isset($this->data['ask_service']) ? $ask_service = $this->data['ask_service'] : $ask_service ='' ;		
            $add_time = date("Y-m-d H:i:s");
            $status = 0;
            //是否申请客服介入
            if($ask_service == "申请客服介入") $status = 2;
            //插入维权信息
			$post = array();
			$post['protectright']['order_id'] = $order_id;
			$post['protectright']['protect_item'] = $protect_item;			
			$post['protectright']['user_id'] = $user_id;
			$post['protectright']['user_type'] ='0';
			$post['protectright']['shop_id'] = $order_info['shop_id'];
			$post['protectright']['content'] = $protect_content;
			$post['protectright']['protect_date'] = $add_time;
			$post['protectright']['status'] = $status;						
            if( POP::exe('[@@:UM protectright][@@:QU save]',$post)) {
	            //修改订单维权状态
	            if(!$order_info['protect_status'])	{
					$query  = array();		
					$query['keyid'] = true;
					$safeData['orderinfo'] = array('protect_status'=>1);				
					$query['set'] = $safeData;	
					$query['conditions'] = array('orderinfo.id'=>$order_id,'orderinfo.user_id'=>$user_id);
					POP::exe('[@@:UM orderinfo][@@:QU save]',$query);				
	            }
				$this->flash("申请维权成功！", Router::url('user/usermyorder/'));				
            } else {
	            $this->flash("申请维权失败！", '-1');
            }		
		
		}else {
		$query = array(
			'conditions' => array('protectright.order_id' => $order_id), 
			'fields' => array('protectright.*'), 
			'order'=>'protect_date DESC',
		);
		$result = POP::exe('[@@:UM protectright][@@:QU find:all]',$query);		

        $is_allow_service = 0;
        $now_time = date("Y-m-d H:i:s",time()-(21*60*60));
		$query = array(
			'conditions' => array('protectright.order_id' => $order_id,'protectright.user_id' =>$user_id,'protectright.user_type' =>0 ), 
			'fields' => array('protectright.*'), 
			'order'=>'protect_date DESC',
		);
		$row = POP::exe('[@@:UM protectright][@@:QU find:first]',$query);			

        if($row){
		    $row = $row['protectright'];
	        if($row['protect_date'] < $now_time) {
		        $is_allow_service = 1;
	        }
        }	
	    $this->set('result',$result);	
	    $this->set('is_allow_service',$is_allow_service);		
	    $this->set('ps',$this->C_session->id());
        $this->set('order_id',$order_id);
        }		
    }	
	
	public function userordercheckget() {
        $order_id = intval($_GET['order_id']);
		if(!$order_id) { exit('非法操作！'); }
		$user_id = $this->my->id;
        //判断商品是否锁定，锁定则不许操作
		$query = array(
				'joins' => array(
					array('type'=>'left','table'=>'ordergoods','conditions'=>array('orderinfo.id' =>'ordergoods.order_id')),					
					),
				'fields' => array('ordergoods.goods_id'),
				'conditions' => array('orderinfo.id' =>$order_id),
				'group' => ''
				);	
	    $row = POP::exe('[@@:UM orderinfo][@@:QU find:all]',$query);

		
        if($row){
		    $rows = array();
		    foreach($row as $k => $v) {
                $rows[$v['b']['goods_id']] = $v['b']['goods_id'];
            }			
	        $goods_id = $rows;
        }
		$query = array(
			'conditions' => array('goods.id' => $goods_id), 
			'fields' => array('goods.*'), 
		);
		$goods = POP::exe('[@@:UM goods][@@:QU find:all]',$query);	
        foreach($goods_id as $vid) {
		    $istrue = array();
            foreach($goods as $v) {
                if($v['goods']['id'] == $vid){
				    $istrue = $v['goods'];
					break;
				} 			
            }
			if(empty($istrue)) { exit( "该订单中有商品不存在");}//没有此商品
        } 	
        foreach($goods as $v) {
            if($v['goods']['lock_flg'] == 1){
				exit('['.$v['goods']['goods_name']."]商品已被锁定");
			}				
        }
        if($this->my->locked==1){
	        $this->C_session->destroy();
	        exit("您已经被锁定了");//非法操作
        }			
		$order_info = array();
		$query = array(
			'conditions' => array('orderinfo.id' => $order_id,'orderinfo.user_id' => $user_id), 
			'fields' => array('orderinfo.*'), 
		);
		$order_info = POP::exe('[@@:UM orderinfo][@@:QU find:first]',$query);	
	
		if(!$order_info ) { exit('该订单不存在！');  }
		$order_info = $order_info['orderinfo'];
		$query = array(
				'joins' => array(
					array('type'=>'left','table'=>'shopinfo','conditions'=>array('shopinfo.id' =>'goods.shop_id')),				
					array('type'=>'left','table'=>'ordergoods','conditions'=>array('ordergoods.goods_id' =>'goods.id')),					
					),
				'fields' => array('ordergoods.goods_id','ordergoods.goods_price','ordergoods.order_num','ordergoods.goods_name','ordergoods.id','goods.goods_thumb','shopinfo.user_id','shopinfo.shop_name'),
				'conditions' => array('ordergoods.order_id' =>$order_info['id'],'shopinfo.id' =>$order_info['shop_id']),
				);	
	    $list = POP::exe('[@@:UM goods][@@:QU find:all]',$query);		
		
		
	    $order_info['order_goods']=$list;	
        if($order_info['order_status']== '0' || $order_info['transport_status'] == '0') {
	        exit("订单状态异常");
        }
		$receive_time = date("Y-m-d H:i:s");
        $post['credit']['order_id']=$order_id;
        $post['credit']['goods_id']=isset($order_info['goods_id'])?$order_info['goods_id']:0;
        $post['credit']['buyer']=$order_info['user_id'];
        $post['credit']['seller']=$order_info['shop_id'];				
		$suc = POP::exe('[@@:UM credit][@@:QU save]',$post);

		$query  = array();		
		$query['keyid'] = true;
		$safeData['orderinfo'] = array('order_status'=>3,'receive_time'=>$receive_time);				
		$query['set'] = $safeData;	
		$query['conditions'] = array('orderinfo.id'=>$order_id,'orderinfo.user_id'=>$user_id);		

        if(POP::exe('[@@:UM orderinfo][@@:QU save]',$query) && $suc) {			
			$this->flash("您已确认收货！", Router::url('user/usermyorder/'));
        } else {			
			$this->flash("确认收货失败", Router::url('user/usermyorder/'));
        }	
    }	
	
	public function getbackmoney() {
        $order_id = intval($_GET['order_id']);
		if(!$order_id) { exit('非法操作！'); }
		$user_id = $this->my->id;
		
		$query = array(
			'conditions' => array('orderinfo.id' => $order_id,'orderinfo.user_id' => $user_id), 
			'fields' => array('orderinfo.*'), 
		);
		$order_info = POP::exe('[@@:UM orderinfo][@@:QU find:first]',$query);			

        $order_info = $order_info['orderinfo'];		
        if (is_array($order_info)) {
	    //判断订单状态
	        if ($order_info['pay_status']==1&&$order_info['order_status']>0&&$order_info['order_status']<3&&time()>(strtotime($order_info['pay_time'])+24*3600)) {
		        $now = date("Y-m-d H:i:s");		
		        if ($order_info['pay_name']=="支付宝纯担保") {//支付宝时可退款
					$query  = array();		
					$query['keyid'] = true;
					$safeData['orderinfo'] = array('get_back_time'=>$now);				
					$query['set'] = $safeData;	
					$query['conditions'] = array('orderinfo.order_id'=>$order_id);		
			        if(POP::exe('[@@:UM orderinfo][@@:QU save]',$query)){				
				        echo "<script language=\"JavaScript\" type=\"text/javascript\">window.open ('http://www.alipay.com');</script>";
			        }
		        }elseif ($order_info['pay_name']=="财付通即时到帐"||$order_info['pay_name']=="财付通中介担保") {//财付通时可退款
					$query  = array();		
					$query['keyid'] = true;
					$safeData['orderinfo'] = array('get_back_time'=>$now);				
					$query['set'] = $safeData;	
					$query['conditions'] = array('orderinfo.order_id'=>$order_id);		
			        if(POP::exe('[@@:UM orderinfo][@@:QU save]',$query)){
				       echo "<script language=\"JavaScript\" type=\"text/javascript\">window.open ('http://www.tenpay.com');</script>";
			        }
		        }else{
					$this->flash("您使用的是线下交易，请与店铺直接联系", Router::url('user/usermyorder/'));
		        }		
				//$this->flash("退款成功", Router::url('user/usermyorder/'));
	        }else{
				$this->flash("您使用的是线下交易，请与店铺直接联系", Router::url('user/usermyorder/'));
	        }
        } else {
	        $this->flash("该订单不存在", Router::url('user/usermyorder/'));
		}	
	}	
	
	public function askbackmoney() {	
        $order_id = intval($_GET['id']);
		if(!$order_id) { exit('非法操作！'); }
		$user_id = $this->my->id;
        //判断商品是否锁定，锁定则不许操作
		$query = array(
				'joins' => array(
					array('type'=>'left','table'=>'ordergoods','conditions'=>array('orderinfo.id' =>'ordergoods.order_id')),					
					),
				'fields' => array('ordergoods.goods_id'),
				'conditions' => array('orderinfo.id' =>$order_id),
				'group' => ''
				);	
	    $row = POP::exe('[@@:UM orderinfo][@@:QU find:all]',$query);

		
        if($row){
		    $rows = array();
		    foreach($row as $k => $v) {
                $rows[$v['b']['goods_id']] = $v['b']['goods_id'];
            }			
	        $goods_id = $rows;
        }
		$query = array(
			'conditions' => array('goods.id' => $goods_id), 
			'fields' => array('goods.*'), 
		);
		$goods = POP::exe('[@@:UM goods][@@:QU find:all]',$query);	
        foreach($goods_id as $vid) {
		    $istrue = array();
            foreach($goods as $v) {
                if($v['goods']['id'] == $vid){
				    $istrue = $v['goods'];
					break;
				} 			
            }
			if(empty($istrue)) { exit( "该订单中有商品不存在");}//没有此商品
        } 	
        foreach($goods as $v) {
            if($v['goods']['lock_flg'] == 1){
				exit('['.$v['goods']['goods_name']."]商品已被锁定");
			}				
        }
        if($this->my->locked==1){
	        $this->C_session->destroy();
	        exit("您已经被锁定了");//非法操作
        }		
		$order_info = array();
		$query = array(
			'conditions' => array('orderinfo.id' => $order_id,'orderinfo.user_id' => $user_id), 
			'fields' => array('orderinfo.*'), 
		);
		$order_info = POP::exe('[@@:UM orderinfo][@@:QU find:first]',$query);			
		
		if(!$order_info ) { exit('该订单不存在！');  }
		$order_info = $order_info['orderinfo'];
		$query = array(
				'joins' => array(
					array('type'=>'left','table'=>'shopinfo','conditions'=>array('shopinfo.id' =>'goods.shop_id')),				
					array('type'=>'left','table'=>'ordergoods','conditions'=>array('ordergoods.goods_id' =>'goods.id')),					
					),
				'fields' => array('ordergoods.goods_id','ordergoods.goods_price','ordergoods.order_num','ordergoods.goods_name','ordergoods.id','goods.goods_thumb','shopinfo.user_id','shopinfo.shop_name'),
				'conditions' => array('ordergoods.order_id' =>$order_info['id'],'shopinfo.id' =>$order_info['shop_id']),
				);	
	    $list = POP::exe('[@@:UM goods][@@:QU find:all]',$query);			
		
		
	    $order_info['order_goods']=$list;
        if($order_info['order_status']=='0') {
	        exit("订单状态异常");
        } elseif ($order_info['order_status']=='3') {
	        exit("此订单已完成不能取消");
        }
        if($order_info['transport_status']=='1') 
        {
	        exit("已经发货，不能再退款！");
        } 
        //判断支付状态，锁定则不许操作
        if ($order_info['pay_status']=='0'){
	        exit("您还没付款，不能退款！");
        } elseif ($order_info['pay_status']=='2') {
	        exit("已经申请退款，请稍等！");
        } elseif ($order_info['pay_status']=='3') {
	        exit("商家已经退款！");
        } elseif ($order_info['pay_status']=='4') {
	        exit("已经退款成功！");
        }

		$query  = array();		
		$query['keyid'] = true;
		$safeData['orderinfo'] = array('pay_status'=>2);				
		$query['set'] = $safeData;	
		$query['conditions'] = array('orderinfo.id'=>$order_id,'orderinfo.user_id'=>$user_id);		
        if(POP::exe('[@@:UM orderinfo][@@:QU save]',$query)) {
			$this->flash("申请退款成功！", Router::url('user/usermyorder/'));
        } else {
			$this->flash("申请退款失败！", '-1');
        }		
	
	}
	
	public function complaint() {
        if (!empty($this->data)) {			
            if(md5(strtolower($this->data['veriCode'])) != $this->C_session->read('captcha')) {
	            exit('验证码错误');	
            }
            $user_id = $this->my->id;
            // 处理post变量
            $post['complaint']['user_id'] = $user_id;
            $post['complaint']['usered_id'] = intval($this->data['shopid']);
            $post['complaint']['goods_id'] = intval($this->data['goods_id']);
            $post['complaint']['usered_name'] = $this->data['shop_name'];
            $post['complaint']['goods_name'] = $this->data['goods_name'];
            $post['complaint']['complaints_title'] = $this->data['complaints_title'];
            $post['complaint']['complaints_content'] = $this->data['complaints_content'];
            $post['complaint']['order_id'] = intval($this->data['order_id']);
            $order=$post['complaint']['order_id'];
            if($this->my->locked==1){
	            $this->C_session->destroy();
	            exit("您已经被锁定了");//非法操作
            }			 

			$insert_id = POP::exe('[@@:UM complaint][@@:QU save]',$post);
            if($insert_id) {			
				$query  = array();		
				$query['keyid'] = true;
				$safeData['orderinfo'] = array('complaint'=>1);				
				$query['set'] = $safeData;	
				$query['conditions'] = array('orderinfo.id'=>$order,'orderinfo.user_id'=>$user_id);		
				POP::exe('[@@:UM orderinfo][@@:QU save]',$query);			
	            $this->flash("添加成功", Router::url('user/usermyorder/'));
            } else {
	            exit("添加失败");	
            } 
		} else {
			$order_id = intval($_GET['order_id']);
			if(!$order_id) { exit('非法操作！'); }
			$user_id = $this->my->id;
			$query = array(
				'conditions' => array('complaint.order_id' => $order_id,'complaint.user_id' => $user_id), 
				'fields' => array('complaint.*'), 
			);
			$row = POP::exe('[@@:UM complaint][@@:QU find:first]',$query);			

			if($row){
				exit('您已经投诉过该商品，请不要重复投诉！');
			}

			$query = array(
					'joins' => array(
						array('type'=>'left','table'=>'shopinfo','conditions'=>array( 'orderinfo.shop_id'=>'shopinfo.id')),				
						array('type'=>'left','table'=>'ordergoods','conditions'=>array( 'orderinfo.id'=>'ordergoods.order_id')),					
						),
					'fields' => array('orderinfo.order_id','orderinfo.payid','orderinfo.shop_id','ordergoods.goods_id','ordergoods.goods_name','orderinfo.order_amount','orderinfo.order_time','orderinfo.order_status','orderinfo.pay_status','orderinfo.transport_status','orderinfo.seller_reply','orderinfo.group_id','shopinfo.user_id','shopinfo.shop_name'),
					'conditions' => array('orderinfo.id' =>$order_id),
					);	
			$order_rs = POP::exe('[@@:UM orderinfo][@@:QU find:all]',$query);		
			
			$query = array(
				'fields' => array('complainttype.*'), 
			);
			$complaints_title = POP::exe('[@@:UM complainttype][@@:QU find:all]',$query);	

			$this->set('complaints_title',$complaints_title); 
			$this->set('order_rs',$order_rs);
			$this->set('order_id',$order_id);
		}
	}

	public function userorderview() {	
		$order_id = $_GET['order_id'];
		if(!$order_id) { exit('非法操作！'); }
		$user_id = $this->my->id;	
		$info  = array();
		$query = array(
			'conditions' => array('orderinfo.id' => $order_id,'orderinfo.user_id' => $user_id), 
			'fields' => array('orderinfo.*'), 
		);
		$info = POP::exe('[@@:UM orderinfo][@@:QU find:first]',$query);		
	
		if(!$info ) { exit('该订单不存在！');  }
		$info = $info['orderinfo'];
		$query = array(
				'joins' => array(
					array('type'=>'left','table'=>'shopinfo','conditions'=>array('shopinfo.id' =>'goods.shop_id')),				
					array('type'=>'left','table'=>'ordergoods','conditions'=>array('ordergoods.goods_id' =>'goods.id')),					
					),
				'fields' => array('ordergoods.goods_id','ordergoods.goods_price','ordergoods.order_num','ordergoods.goods_name','ordergoods.id','goods.goods_thumb','shopinfo.user_id','shopinfo.shop_name'),
				'conditions' => array('ordergoods.order_id' =>$info['id'],'shopinfo.id' =>$info['shop_id']),
				);	
	    $list = POP::exe('[@@:UM goods][@@:QU find:all]',$query);			

	    $info['order_goods']=$list;
		
		$query = array(
			'fields' => array('area.*'), 
		);
		$return_array = POP::exe('[@@:UM area][@@:QU find:all]',$query);	

	    $areas = array();		
	    foreach($return_array as $k=>$v) {
		    $areas[$v['area']['id']] = $v['area']['area_name'];
	    }
        $this->set('info',$info);
        $this->set('areas',$areas);		
	}	

	
	public function userordersuccess() {	
        $payid = $_GET['id'];
		$orderid = $_GET['orderid'];
        if(!$payid) { exit('非法操作！'); }
		if(!$orderid) { exit('非法操作！'); }
		$this->set('payid',$payid);
		$this->set('orderid',$orderid);
	}

	public function paymentmsg() {	
        $order_id = intval($_GET['id']);
		$user_id = $this->my->id;
        if(!$order_id) { exit('非法操作！');  }
		
		$query = array(
				'joins' => array(
					array('type'=>'left','table'=>'ordergoods','conditions'=>array('orderinfo.id' =>'ordergoods.order_id')),					
					),
				'fields' => array('ordergoods.goods_id'),
				'conditions' => array('orderinfo.id' =>$order_id),
				'group' => ''
				);	
	    $row = POP::exe('[@@:UM orderinfo][@@:QU find:first]',$query);			

        if($row){
	        $goods_id=$row['ordergoods']['goods_id'];
        }
		
		$query = array(
				'fields' => array('user.locked'),
				'conditions' => array('user.id' =>$user_id),
				);	
	    $row = POP::exe('[@@:UM user][@@:QU find:first]',$query);	

        if($row['user']['locked']==1){
            $this->C_session->destroy();			
			$this->flash('您已经被锁定了', '-1');
        }
		$order_info = array();
		$query = array(
			'conditions' => array('orderinfo.id' => $order_id,'orderinfo.user_id' => $user_id), 
			'fields' => array('orderinfo.*'), 
		);
		$order_info = POP::exe('[@@:UM orderinfo][@@:QU find:first]',$query);		
	
		if(!$order_info ) { exit('该订单不存在！');  }
		$order_info = $order_info['orderinfo'];
		
		$query = array(
				'joins' => array(
					array('type'=>'left','table'=>'shopinfo','conditions'=>array('shopinfo.id' =>'goods.shop_id')),				
					array('type'=>'left','table'=>'ordergoods','conditions'=>array('ordergoods.goods_id' =>'goods.id')),					
					),
				'fields' => array('ordergoods.goods_id','ordergoods.goods_price','ordergoods.order_num','ordergoods.goods_name','ordergoods.id','goods.goods_thumb','shopinfo.user_id','shopinfo.shop_name'),
				'conditions' => array('ordergoods.order_id' =>$order_info['id'],'shopinfo.id' =>$order_info['shop_id']),
				);	
	    $list = POP::exe('[@@:UM goods][@@:QU find:all]',$query);			
		
	    $order_info['order_goods']=$list;
        if($order_info['order_status']=='0'||$order_info['order_status']=='3'||$order_info['pay_status']=='1'){
	        exit('非法操作！'); 
        }
		$query = array(
			'conditions' => array('shoppayment.shop_id' => $order_info['shop_id'],'shoppayment.enabled'=>1), 
			'fields' => array('shoppayment.*'), 
		);
		$rowset = POP::exe('[@@:UM shoppayment][@@:QU find:all]',$query);		
		
	    $payment_shop_info = array();
	    if($rowset) {
		    foreach($rowset as $info) {
			    $temp = unserialize($info['shoppayment']['pay_config']);
			    if(is_array($temp)){
				    $info['shoppayment'] = array_merge($info['shoppayment'], $temp);
			    }
			    $payment_shop_info[$info['shoppayment']['pay_id']] = $info['shoppayment'];
		    }
	    }	
		$query = array(
			'conditions' => array('payment.enabled'=>1), 
			'fields' => array('payment.*'), 
		);
		$array = POP::exe('[@@:UM payment][@@:QU find:all]',$query);	

	    $payment_info = array();
	    foreach($array as $value) {
		    $payment_info[$value['payment']['id']] = $value['payment'];
	    }
        $this->set('order_info',$order_info);	
        $this->set('payment_info',$payment_info);
        $this->set('payment_shop_info',$payment_shop_info);		
		
	}	
	
	public function usermyorder() {	
		if(!isset(Request::$query['page']))Request::$query['page']=1;
        $page = intval(Request::$query['page']);	
        if(isset($_GET['state'])){ $state=intval($_GET['state']); } else {$state=''; }
		$user_id = $this->my->id;
        $conditions = array();
		$conditions['orderinfo.order_status >'] = "0";
		$conditions['orderinfo.user_id'] = $user_id;		
	    if(!empty($state)){
			switch ($state){
				case 1:
					$conditions['orderinfo.order_status'] = "1";
					break;
				case 2:
					$conditions['orderinfo.order_status'] = "2";
					break;
				case 3:
					$conditions['orderinfo.pay_status'] = "0";					
					break;					
				case 4:
					$conditions['orderinfo.pay_status'] = "1";					
					break;						
				case 5:
					$conditions['orderinfo.transport_status'] = "0";					
					break;						
				case 6:
					$conditions['orderinfo.transport_status'] = "1";					
					break;						
				case 7:
					$conditions['orderinfo.order_status'] = "3";			
					break;					
				case 8:
					$conditions['orderinfo.order_status <>'] = "3";
					$conditions['orderinfo.transport_status'] = "1";					
					break;				
				case 9:
					$conditions['orderinfo.order_status'] = "3";
					$conditions['orderinfo.buyer_reply'] = "0";				
					break;
			}
		}	

        $url_this = 'http://'.$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
        $tb = array('model' => 'orderinfo',
 		            'joins' => array(
					    array('type'=>'left','table'=>'shopinfo','conditions'=>array('orderinfo.shop_id' =>'shopinfo.id')),					
						),
				    'fields' => array('orderinfo.*','shopinfo.shop_name','shopinfo.id','shopinfo.open_flg','shopinfo.lock_flg'),
					'conditions' => $conditions,
					'order' => ' orderinfo.order_time desc ',
					'limit' => '10',
					'group' => '',
					'url' => preg_replace("/&page=([^&]+)/","",$url_this),
					'page' => $page,
					'plist' => 6				
				); 
	    $result =  $this->fpage($tb); 		
		
	    foreach ($result['data'] as $k=>$v){
			$query = array(
					'joins' => array(
						array('type'=>'left','table'=>'shopinfo','conditions'=>array('shopinfo.id' =>'goods.shop_id')),				
						array('type'=>'left','table'=>'ordergoods','conditions'=>array('ordergoods.goods_id' =>'goods.id')),					
						),
					'fields' => array('ordergoods.goods_id','ordergoods.goods_name','ordergoods.id','goods.goods_thumb','shopinfo.user_id','shopinfo.shop_name','shopinfo.lock_flg'),
					'conditions' => array('ordergoods.order_id' =>$v['orderinfo']['id'],'shopinfo.id' =>$v['orderinfo']['shop_id']),
					);	
			$goods_list = POP::exe('[@@:UM goods][@@:QU find:all]',$query);		

		    $result['data'][$k]['order_goods']=$goods_list;
	    }
        $this->set('result',$result);
	}	


	function _sendGetPasswdConfirmEmail($addr, $username, $ConfirmationCode) {
		$this->Email->to = $addr;
		$this->Email->bcc = array('noreply@ggl.com');  
		$this->Email->subject = 'GGL Reset Password Confirmation';
		$this->Email->replyTo = 'noreply@ggl.com';
		$this->Email->from = '"GGL" <noreply@ggl.com>';
		$this->Email->template = 'confirm_getpasswd'; // note no '.ctp'
		//Send as 'html', 'text' or 'both' (default is 'text')
		$this->Email->sendAs = 'both'; // because we like to send pretty mail
		//Set view variables as normal
		$this->set('user', $username);
		$this->set('ConfirmationCode', $ConfirmationCode);
		
		//------ 采用SMTP方式发送邮件
		//SMTP Options
		$this->Email->smtpOptions = array(
			'port'=>'465', 
			'timeout'=>'30',
			'host' => 'ssl://smtp.gmail.com',
			'username'=>'noreply@ggl.com',
			'password'=>'zxcvl#8v',
		);

		//Set delivery method 
		//使用SMTP方式需要确认的是：libs/controller/components/email.php 中的 HELO 修改为 EHLO (1.3版本不再需要修改)
		//email.php更改成var $xMailer = 'GGL Email';
		$this->Email->delivery = 'smtp';

		//------ SMTP设置完成，如要使用PHP函数发送邮件，则直接注释该部分		
		
		//Do not pass any args to send()
		$this->Email->send();	
	}


}


?>